package com.demo.cms.webapp.template.directive;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.demo.cms.model.Article;
import com.demo.cms.service.ArticleService;
import com.demo.webapp.views.freemarker.directive.core.PageContextDirectiveSupport;

import freemarker.core.Environment;
import freemarker.core.Environment.TemplateDirectiveBodyEx;
import freemarker.template.SimpleHash;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;

public class ArticleDirective extends PageContextDirectiveSupport {

	/**
	 * 页面模板名
	 */
	private static final String ARTICLE_TEMPLATE_NAME = "classpath:/com/demo/cms/webapp/template/article.ftl";
	
	/**
	 * 文章数据服务
	 */
	@Autowired
	private ArticleService articleService;

	@SuppressWarnings("rawtypes")
	@Override
	public void preWriter(Environment env, TemplateDirectiveBodyEx bodyEx,
			TemplateModel[] loopVars, SimpleHash hash, Map params)
			throws IOException, TemplateException {
		
		Long id = null;
		boolean content = false;
		//SimpleNumber
		id = getLong("id", params);
		content = getBoolean("content", params, Boolean.valueOf(getDefaultValue("content")));
		Article article = null;
		//  是否包含文章内容
		if (content) {
			article = articleService.query(id);
		} else {
			article = articleService.find(id);
		}
		// 
		hash.put("article", article);
	}

	@SuppressWarnings("rawtypes")
	@Override
	public String getTemplatePath(Map params) {
		String path = "";
		try {
			path = getString("path", params, ARTICLE_TEMPLATE_NAME);
		} catch (TemplateModelException e) {}
		return path;
	}
	
	@Override
	public void afterInvoke(Writer writer) {
		
	}
}
